package com.trtan.hr.service;

import com.trtan.hr.dao.HrDao;
import com.trtan.hr.pojo.Hr;
import com.trtan.hr.pojo.Menu;
import com.trtan.hr.pojo.RespPageEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HrService implements UserDetailsService {
    @Autowired
    HrDao hrDao;

    /**
     * loadUserByUsername在用户登录时会被自动调用
     * 流程：用户登录时输入用户名密码->通过用户名去数据库查找用户(没有查找则抛出账户不存在异常)->
     * 用户存在则查找用户的角色信息->将获取到的用户hr对象返回->DaoAuthenticationProvider类对比密码是否正确
     * @param username 登录时输入的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Hr hr = hrDao.loadUserByUsername(username);
        if (hr == null) {
            throw new UsernameNotFoundException("账户不存在");
        }
        hr.setRoles(hrDao.getUserRoleByUid(hr.getId()));
        return hr;
    }

    public RespPageEntity queryAll(Integer page, Integer size, String username) {
        RespPageEntity entity = new RespPageEntity();
        if (page != null && size != null) {
            page = (page - 1) * size;
        }
        List<Hr> hrs = hrDao.queryAllHr(page, size, username);
        entity.setData(hrs);
        Long total = hrDao.getTotal(username);
        entity.setTotal(total);
        return entity;
    }

    public void addHr(Hr hr) {
        hrDao.addHr(hr);
    }

    public void modifyHr(Hr hr) {
        hrDao.modifyHr(hr);
    }

    public void deleteHr(Integer id) {
        hrDao.deleteHrById(id);
    }


}
